package com.bike.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.ehcache.search.impl.BaseResult;

public class ImageUtil {

	public static String uploadImage(String foldname,MultipartFile imgfile){
		try {
			if(imgfile==null){
				return null;
			}
			//原始名称
			String originalFilename = imgfile.getOriginalFilename();
			//上传图片
			if( originalFilename!=null && originalFilename.length()>0){
				String msg="";
				String imgtype=originalFilename.substring(originalFilename.lastIndexOf("."));
				if(imgfile.getSize()>1024*1024*10){
					msg="图片大小超过规定数值!";
				}else if(".jpg".equalsIgnoreCase(imgtype)
						|| ".peg".equalsIgnoreCase(imgtype)
						|| ".png".equalsIgnoreCase(imgtype)
						|| ".jpng".equalsIgnoreCase(imgtype)
						|| ".jpeg".equalsIgnoreCase(imgtype)
						|| ".pjpeg".equalsIgnoreCase(imgtype)
						|| ".x-png".equalsIgnoreCase(imgtype)
						|| ".gif".equalsIgnoreCase(imgtype)){
					StringBuffer targetFile=new StringBuffer(Constant.NATIVEPATH);
					TimeManager  timeManage=TimeManager.getInstance();
					
					String fileFold=new StringBuffer().append(foldname)
								.append("/")
								.append(timeManage.getYear())
								.append("/")
								.append(timeManage.getMonth())
								.append("/")
								.toString();
					String fileName=new StringBuffer(UUID.randomUUID().toString().replaceAll("-",""))
													.append(imgtype).toString();		
					File fold=new File(targetFile.append(fileFold).toString());
					if(!fold.exists()){
						fold.mkdirs();
					}
					
					File newFile = new File(fold,fileName);
					imgfile.transferTo(newFile);
					return new StringBuffer().append(Constant.URLPATH).append(fileFold).append(fileName).toString();
				}else{
					msg="图片格式错误";
				}
				return null;
			}
		} catch (IllegalStateException e) {
			 e.printStackTrace();
		} catch (IOException e) {
			 e.printStackTrace();
		}
		return null;
		
	}
	
	 
	public static void main(String[] args) throws IOException {
	}
}
